const db = require('../model/db')
const Base = require('./base')
const utils = require('root/utils')
const config = require('root/config')
const jwt = require('jsonwebtoken')

const TableName = 'tk_user'

class User extends Base {
  // 注册
  async register(req, res) {
    const { username, password } = req.body
    const app_id = req.headers.appid || 1
    const sql1 = `select * from ${TableName} where username=? and app_id=${app_id}`
    const [rows] = await db.query(sql1, username)

    if (rows.length > 0) {
      return res.cc('用户名被占用，请更换其他用户名！')
    }

    const sql2 = `insert into ${TableName} set ?`
    const hashPwd = utils.md5Pwd(password)

    delete req.body.password

    const [rows2] = await db.query(sql2, { username, app_id, password: hashPwd, ...req.body })

    if (rows2.affectedRows !== 1) {
      return res.cc('注册用户失败，请稍后再试！')
    }

    return res.cc('注册成功！', 0)
  }

  // 登录
  async login(req, res) {
    const { username, password } = req.body
    const app_id = req.headers.appid || 1
    const sql1 = `select * from ${TableName} where username=? and app_id=${app_id}`
    const [rows] = await db.query(sql1, username)
    const profile = { username }

    if (rows.length !== 1) {
      return res.cc('用户名不存在！')
    }

    if (utils.md5Pwd(password) === rows[0].password) {
      const token = jwt.sign(profile, config.secretKey, {
        expiresIn: 36000, // 60*10 minutes
      })

      return res.cc('success', 0, { data: { token, user: rows[0] } })
    }

    return res.cc('密码错误')
  }

  // 获取所有用户
  async findAll(req, res) {
    const { username, page, limit } = req.query
    const currentPage = parseInt(page || 1)
    const pageSize = parseInt(limit || 10)
    const startIndex = (currentPage - 1) * pageSize
    const app_id = req.headers.appid || 1
    const data = { total: 0, rows: [] }
    const sql1 = `select
      id, username, nickname, sex, avatar, description, loginip, logintime, verify, email, isadmin, status, address, app_id, create_time, update_time
      from ${TableName} where app_id = ${app_id} and username LIKE ? LIMIT ?, ?`
    const sql2 = `select count(*) as total from ${TableName} where app_id = ${app_id} and username LIKE ?`

    const [rows] = await db.query(sql1, [`%${username || ''}%`, startIndex, pageSize])
    const [[{ total }]] = await db.query(sql2, [`%${username || ''}%`])

    if (rows.length > 0) {
      data.rows = rows
      data.total = total
    }

    return res.cc('success', 0, { data })
  }

  // 详情
  async findOne(req, res) {
    const { id } = req.params
    const data = { total: 0, rows: '' }
    const sql = `select * from ${TableName} where id = ?`

    const [[rows]] = await db.query(sql, [id])

    if (rows) {
      data.rows = rows
      delete rows.password
    }

    return res.cc('success', 0, { data })
  }

  // 修改密码
  async changePassword(req, res) {
    const { id } = req.params
    const { password, newPassword, confirmPassword } = req.body
    const sql = `select * from ${TableName} where id = ? and password=?`
    const md5Password = utils.md5Pwd(password)

    const [[rows]] = await db.query(sql, [id, md5Password])

    if (!rows) {
      return res.cc('修改的用户不存在或密码不正确')
    }

    if (!newPassword || !confirmPassword) {
      return res.cc('新密码不能为空')
    }

    if (newPassword !== confirmPassword) {
      return res.cc('两次输入的密码不一致')
    }

    const newMd5Password = utils.md5Pwd(newPassword)
    const sql2 = `update ${TableName} set password=? where id=?`

    const [rows2] = await db.query(sql2, [newMd5Password, id])

    if (!rows2.affectedRows) {
      return res.cc('修改失败！')
    }

    return res.cc('success', 0, { data: rows2 })
  }

  async create(req, res) {
    await this.baseCreate(req, res)
  }

  async update(req, res) {
    await this.baseUpdate(req, res)
  }

  async remove(req, res) {
    await this.baseRemove(req, res)
  }
}

module.exports = User
